package ioc

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"shop_srvs/goods_srv/global"
	"time"
)

func InitDB() {
	type MysqlConfig struct {
		UserName string `json:"userName"`
		Password string `json:"password"`
		Address  string `json:"address"`
		DB       string `json:"db"`
	}
	var c MysqlConfig
	err := viper.UnmarshalKey("mysql", &c)
	if err != nil {
		panic(err)
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4"+
		"&parseTime=True&loc=Local", c.UserName, c.Password, c.Address, c.DB)
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		})
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{SingularTable: true},
		Logger:         newLogger,
	})
	if err != nil {
		panic(err)
	}
}
